package com.qp.basics.admin.controller;

import com.qp.basics.admin.service.dto.OauthTokenReq;
import com.qp.basics.auth.config.bean.SecurityProperties;
import com.qp.basics.common.domain.UserInfo;
import com.qp.basics.common.exception.BadRequestException;
import com.qp.basics.common.feign.JwtToken;
import com.qp.basics.common.feign.OAuth2FeignClient;
import com.qp.basics.common.repository.BaseRepository;
import com.qp.basics.common.utils.RedisUtils;
import com.qp.basics.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.util.Base64Utils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/oauth")
public class OauthController {

    @Autowired
    private BaseRepository<UserInfo, Long> userInfoRepository;

    @Autowired
    private UserDetailsService userDetailsService;

    private RandomValueStringGenerator generator = new RandomValueStringGenerator(16);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SecurityProperties properties;

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    public static final String type_client = "client";//移动端
    public static final String type_console = "console";//管理端
    public static final String code_key = "oauth-code:";
    public static final String oauth_client_token ="oauth-client-token:";

    @GetMapping("/userInfo")
    public ResponseEntity userInfo(HttpServletRequest req, @RequestParam("code") String code, @RequestParam("clientType") String clientType) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "未授权");
        }
        String value = (String) redisUtils.get(code_key+code);
        if (StringUtils.isEmpty(value)) {
            return new ResponseEntity("code不存在", HttpStatus.NOT_FOUND);
        }
//        redisUtils.del(code_key+code);
        Object o = null;
        if (type_console.equals(clientType)) {//管理端
            o = userDetailsService.loadUserByUsername(value);
        } else if (type_client.equals(clientType)) {//移动端
            //婚姻 loveStatus，性别 sex，姓名 nickName，身份证号码 idCard，出生年月 birthday，手机号 mobile，公司id company_id，教育类型 education，工会ID clubCard，年龄 age
            String sql = "select ui.id, ui.username , ui.mobile , love_status as loveStatus, sex, ui.nick_name as nickName, id_card as idCard, birthday, education, age, club_card clubCard,ui.company_id as companyId," +
                    " cm.title AS companyName," +
                    " d.`name`AS unionName," +
                    " pd.`name` AS punionName " +
                    " from sys_user_info ui " +
                    " left join hr_company cm on cm.id=ui.company_id\n" +
                    " left join sys_dept d on d.dept_id=ui.f_dept_id\n" +
                    " left join sys_dept pd on pd.dept_id=d.pid " +
                    "where ui.id="+Long.parseLong(value);

            List tmp=userInfoRepository.findMapByNativeSql(sql,null);
            if(tmp!=null&&tmp.size()>0){
                o=tmp.get(0);
            }
        }
        return ResponseEntity.ok(o);
    }

    @GetMapping("/genCode")
    public ResponseEntity genCode(Principal principal, HttpServletRequest req, @RequestParam("clientType") String clientType) {
        String code = null;
        if (type_console.equals(clientType)) {//管理端
            if (principal == null) {
                throw new BadRequestException(HttpStatus.UNAUTHORIZED, "未授权");
            }
            String name = principal.getName();//用户名
            code = generator.generate();
//            redisUtils.set(code_key+ code, name, 300);
            redisUtils.set(code_key+ code, name, 1, TimeUnit.DAYS);
        } else if (type_client.equals(clientType)) {//移动端
            String userInfoId = req.getHeader("auth-user-id");
            if (!StringUtils.isEmpty(userInfoId) && !"undefined".equals(userInfoId)) {
                code = generator.generate();
//                redisUtils.set(code_key+code, userInfoId, 300);
                redisUtils.set(code_key+code, userInfoId, 1, TimeUnit.DAYS);
            }
        }
        if (code != null) {
            return ResponseEntity.ok(code);
        } else {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "未授权");
        }
    }


    @PostMapping("/token")
    public ResponseEntity token(@Validated @RequestBody OauthTokenReq req){
        String basicToken= Base64Utils.encodeToString((req.getClientId()+":"+req.getClientSecret()).getBytes());
        ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken(req.getGrantType(),req.getUsername(),req.getPassword(),null,"Basic "+ basicToken);
        if(tokenResponseEntity.getStatusCode()!= HttpStatus.OK){
            throw new BadRequestException("授权失败") ;
        }
        JwtToken jwtToken = tokenResponseEntity.getBody();
        long expiresIn=jwtToken.getExpiresIn();
        String token = jwtToken.getAccessToken() ;
        redisUtils.set(oauth_client_token+token,1,expiresIn);
        return ResponseEntity.ok(jwtToken);
    }
}
